package cn.rui.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义线程池
 *
 * @author 徽州大都督
 * @date 2021/5/31
 */

@Configuration
@EnableAsync
public class ExecutorConfig {

    @Bean("taskExecutors")
    public Executor asyncThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor ();
        //设置核心线程数
        executor.setCorePoolSize (5);
        //设置最大线程数
        executor.setMaxPoolSize (20);
        //配置队列大小
        executor.setQueueCapacity (Integer.MAX_VALUE);
        //设置线程活跃时间(秒)
        executor.setKeepAliveSeconds (60);
        //设置线程名称
        executor.setThreadNamePrefix ("李小瑞的线程池");
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown (true);
        //
        executor.setAwaitTerminationSeconds (10);
        //线程池对拒绝任务的处理策略：这里采用了CallerRunsPolicy策略，
        // 当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；
        // 如果执行程序已关闭，则会丢弃该任务
        executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ());
        executor.initialize ();
        return executor;
    }
}
